class Solution
{
    bool st[100010];
public:
    long long totalCost(vector<int>& costs, int k, int cs)
    {
        long long ans = 0;
        int n = costs.size();
        priority_queue<int, vector<int>, greater<int>> pq_left;
        priority_queue<int, vector<int>, greater<int>> pq_right;
        int left = 0;
        int right = n - 1;
        while (left < cs)
        {
            st[left] = true;
            pq_left.push(costs[left++]);
        }
        for (int i = 0; i < cs && right >= left; i++, right--)
        {
            if (!st[right])
            {
                st[right] = true;
                pq_right.push(costs[right]);
            }
        }
        while (k)
        {
            int mn = 0x3f3f3f3f;
            int flag = 0;
            if (!pq_right.empty())
            {
                mn = min(mn, pq_right.top());
                flag = 1;
            }

            if (!pq_left.empty())
            {
                if (mn >= pq_left.top())
                {
                    mn = min(mn, pq_left.top());
                    flag = 2;
                }
            }
            if (flag == 0) break;
            if (flag == 1)
            {
                pq_right.pop();
                if (right >= left && !st[right])
                {
                    st[right] = true;
                    pq_right.push(costs[right--]);
                }
            }
            if (flag == 2)
            {
                pq_left.pop();
                if (left < n && !st[left])
                {
                    st[left] = true;
                    pq_left.push(costs[left++]);
                }
            }
            ans += mn;
            k--;
        }

        return ans;
    }
};